package com.feijia.aijingjingus;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.text.TextUtils;
import com.clj.fastble.BleManager;
import com.junkchen.blelib.BleService;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import static java.lang.System.in;
import static java.lang.System.out;

/**
 * Created by 菲伽 on 2017/4/21.
 */

public class GlobalHelper {
    public static String GUserNum = "",AssociatedUser = "";
    public static String NickName = "", FirstDay = "", LastDay = "";
    public static int Menstruation,PeriodLength;
    public static int Sex;
    public static BleService mBleService;
    public static boolean mIsBleConnected=false;
    public static boolean mIsBind=false;
    public static boolean mNeedRescan=true;
    public static boolean mIsTimeUnbide=false;
    public static boolean ShowLocalDetection =true;
    public static boolean NeedUploadDetection =false;
    public static JSONObject NeedUploadDetectionData;
    public static String DetectionDatetime ="";
    public static String Report = "";
    public static String tip = "";
    public static String RawDetectionData = "";
    public static double UploadRawDetectionData=-10;
    public static String DetectionResults = "";
    public static String DetectionLocation = "";
    public static String DetectionType = "HCG";

    public static boolean isBleRescanThreadRunning=false;
    public static long BleScanTime = 315360000000L;
    public static final long ONE_DAY_MS=24*60*60*1000;
    public static int DaysBeforeOvulation =10;
    public static int OvulationLength =10;

    public static String BleAddress="";

    public static final boolean DEBUG_MODE  = false;
    public static final boolean DEBUG_MODE_SHOW_AD  = true;
    public static final boolean DEBUG_MODE_SHOW_TOAST_AD  = false;
    public static final boolean SHOW_DYNAMIC_VALUE  = true;

    public static Handler handler;

    //ChenYang
    public final static UUID CYUUID_RX =
            UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
    public final static UUID CYUUID_TX =
            UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    public final static UUID CYUUID_SERVICE =
            UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    public static boolean CYConn=true;

    public static int BleR=0;
    public static int BleG=0;
    public static int BleB=0;
    public static boolean ShowRGB=false;

    public static int ReadCount=0;
    public static int AD1=0;
    public static int AD2=0;
    public static boolean ShowAD=true;

    public static boolean TestPCB=true;

    public final static UUID UUID_RX =
            UUID.fromString("0783b03e-8535-b5a0-7140-a304d2495cb8");
    public final static UUID UUID_TX =
            UUID.fromString("0783b03e-8535-b5a0-7140-a304d2495cba");
    public final static UUID UUID_SERVICE =
            UUID.fromString("0783b03e-8535-b5a0-7140-a304d2495cb7");

    public static BluetoothGattCharacteristic rxCharacteristic=null;
    public static BluetoothGattCharacteristic txCharacteristic=null;
    public static BluetoothGattCharacteristic SERVICECharacteristic=null;
    public static ServiceConnection serviceConnection=null;
    public static boolean StartDetecting=false;
    public static int BleBeatsSpan = 5;
    public static int BleDisconnCountDown=BleBeatsSpan;
    public static int BleReadCount=0;
    public static final int BleDataSize = 2;
    public static int[] BleData = new int[BleDataSize];
    public static Handler BleHandler = null;
    public static final int BleBufferSize = 8;
    public static int[] BleBuffer = new int[BleBufferSize];
    public static final int NewestDetectDataBufferSize = 3;
    public static final int NewestDetectDataBufferTwoSize = 3;
    public static int NewestDetectDataCount=0;
    public static float[] NewestDetectDataBuffer = new float[NewestDetectDataBufferSize];
    public static float[] NewestDetectDataBufferTwo = new float[NewestDetectDataBufferTwoSize];
    public static ArrayList<Integer> AD1List = new ArrayList<>();
    public static ArrayList<Integer> AD2List = new ArrayList<>();
    public static boolean  TemperatureDetect=false;
    //public static double MenstruationLength=28;

    public static boolean isPlayedGuideAni=false;

    public static boolean IsFirstTimePlayAni=true;
    public static boolean SkipLogo=false;

    public static final int REQUEST_FINE_LOCATION=0;

    public static int BatteryValue=999;
    public static int Mode=1;
    public static boolean isBleConnectingOrConnected=true;
    public static BleManager bleManager;

    public static int DNum=0;
    public static ArrayList<Integer> ADRecord= new ArrayList<Integer>();
    public static boolean isCheckingNet=false;
    public static ConnectivityManager NetConnectivityManager;
    public static boolean isNetOut=false;
    public static boolean isNeedInitBle = false;
    public static int TempThreshold = 1100;
    public static double Temperature=0;
    public static String DeviceName;

    public static JSONObject PostData(JSONObject post, String url) {
        String POSTresult = "";
        try {
            PrintWriter out;
            BufferedReader in;
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            String method = "POST";
            String accept = "application/json";
            String content_type = "application/json";
            conn.setRequestProperty("content-type", content_type);
            conn.setRequestProperty("accept", accept);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            String body = post.toString();
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(body);
            System.out.println(body);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            InputStream is;
            HttpURLConnection httpconn = (HttpURLConnection) conn;
            if (httpconn.getResponseCode() == 200) {
                is = httpconn.getInputStream();
            } else {
                is = httpconn.getErrorStream();
            }
            InputStreamReader sr = new InputStreamReader(is, "utf-8");
            in = new BufferedReader(sr);
            String line;
            while ((line = in.readLine()) != null) {
                POSTresult += line;
            }
        } catch (Exception e) {
            out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        // 解析请求结果
        JSONObject resultObj = new JSONObject();
        try {
            resultObj = new JSONObject(POSTresult);
        } catch (JSONException e) {
            System.out.print("错误的返回:"+POSTresult);
            e.printStackTrace();
        }
        return resultObj;
    }

    public static JSONObject SelectDetectionData(JSONObject data, String time) {
        try {
            for (int i=0 ;i<data.getInt("ResultCount");i++){
                JSONObject singleObject = new JSONObject(data.getString(""+i));
                String dataTime =singleObject.getString("DetectionDate").substring(11);
                if (time.equals(dataTime))
                    return singleObject;
            }
            return null;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject SelectDetectionData(JSONObject data, boolean isnewest) {
        if (isnewest)
            try {
                return new JSONObject(data.getString("0"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        else {
            try {
                return new JSONObject(data.getString((data.getInt("ResultCount")-1)+""));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static String bytesToHexString(byte[] bytes) {
        String result = "";
        for (int i = 0; i < bytes.length; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            result += hexString.toUpperCase();
        }
        return result;
    }
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static int CalculateDaysBetweenDate(Date startDate,Date endDate)
    {
        return (int)((endDate.getTime()-startDate.getTime())/ONE_DAY_MS);
    }

    public static int isPingSuccess(int pingNum, String m_strForNetAddress) {
        StringBuffer tv_PingInfo = new StringBuffer();
        try {

            Process p = Runtime.getRuntime()
                    .exec("/system/bin/ping -c " + pingNum + " -s 128 -w 2000 "
                            + m_strForNetAddress);
            // m_strForNetAddress
            int status = p.waitFor();
            return status;
        } catch (Exception ex) {
            ex.printStackTrace();
            return -1;
        }

    }
}
